package com.jiangyg.mall.authz.support.authentication;

import com.jiangyg.mall.core.support.restful.Result;
import com.jiangyg.mall.core.utils.Logger;
import com.jiangyg.mall.core.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 类描述：认证异常相关处理
 *
 * @author jiangyg
 * @version 4.0
 * @date 2021-10-09
 */
@Slf4j
public class AuthErrorExceptionHandler implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) {
        Logger.info(log, () -> String.format("请求[%s]认证异常：", WebUtils.getRequestPath(request)), ex);
        // Token已过期
        if (ex instanceof CredentialsExpiredException) {
            WebUtils.out(response, Result.instance("422"));
            return;
        }
        // 鉴权失败
        WebUtils.out(response, Result.instance("421"));
    }

}
